import React, { Component } from 'react'
import Info from "components/info";
import { deepFullCopy, messages } from "share/common";
import periodControlService from 'containers/finance-setting/period-control/period-control.service'
import AdvanceTable from 'components/advanced-table';
import { Tabs, Button, Badge, Checkbox, notification, Icon, message } from "antd";
import moment from "moment";
import httpFetch from "share/httpFetch";
import 'styles/pay-setting/account-detail.scss'

class PeriodControlDetail extends Component {

  attributes = [
    { title: messages('finance-5.key1')/*会计期编码*/, dataIndex: 'periodSetCode' },
    { title: messages('finance-5.key2')/*会计期名称*/, dataIndex: 'periodSetName' },
    { title: messages('finance-5.key3')/*期间总数*/, dataIndex: 'totalPeriodNum' },
    { title: messages('finance-5.key31')/*账套编码*/, dataIndex: "setOfBooksCode" },
    { title: messages('finance-5.key32')/*账套名称*/, dataIndex: 'setOfBooksName' }
  ];

  columns = [
    { title: messages('common.sequence')/*序号*/, dataIndex: 'periodNum' },
    { title: messages('finance-5.key33')/*年*/, dataIndex: 'periodYear' },
    {
      title: messages('finance-5.key9')/*日期从*/, dataIndex: 'startDate',
      render: date => moment(date).format('YYYY-MM-DD')
    },
    {
      title: messages('finance-5.key34')/*日期至*/, dataIndex: 'endDate',
      render: date => moment(date).format('YYYY-MM-DD')
    },
    { title: messages('finance-5.key12')/*季度*/, dataIndex: 'quarterNum' },
    { title: messages('finance-5.key35')/*期间*/, dataIndex: 'periodName' },
    {
      title: messages('finance-5.key36')/*期间状态*/, dataIndex: 'periodStatusCode',
      render: code => (
        <Badge
          status={code === 'O' ? 'success' : 'error'}
          text={code === 'N' ? messages('finance-5.key37')/*未打开*/ :
            (code === 'O' ? messages('finance-5.key38')/*已打开*/ :
              messages('finance-5.key39')/*已关闭*/)}
        />
      )
    }
  ];

  state = {
    info: {},
    infoLoading: false,
    isEditing: false,
    columns: deepFullCopy(this.columns),
    checkedId: [],
    radio: 'close'
  };

  componentWillMount() {
    this.getInfo();
  }

  getInfo = () => {
    const { periodSetId, setOfBooksId } = this.props.params;
    this.setState({ infoLoading: true });
    periodControlService.getAccountPeriodInfo(periodSetId, setOfBooksId)
      .then(res => {
        this.setState({ info: res.data });
      })
      .finally(() => {
        this.setState({ infoLoading: false });
      })
  };

  renderButton = () => {
    const { isEditing, editLoading } = this.state;
    return isEditing ? <div style={{ marginBottom: '12px' }}>
      <Button onClick={this.handleEdit} type='primary' loading={editLoading}>{messages('common.ok')/*确定*/}</Button>
      <Button onClick={this.handleGoView} style={{ marginLeft: '8px' }}>{messages('common.cancel')/*取消*/}</Button>
    </div> : <div style={{ marginBottom: '12px' }}>
      <Button onClick={this.handleGoEdit} type='primary'>{messages('common.edit')/*编辑*/}</Button>
    </div>;
  };

  handleEdit = () => {
    const { periodSetId, setOfBooksId } = this.props.params, { checkedId, radio } = this.state;
    if (checkedId.length) {
      this.setState({ editLoading: true });
      periodControlService[(radio === 'open' && checkedId[0].periodStatusCode !== 'O') ? 'closePeriod' : 'openPeriod']({
        periodSetId, setOfBooksId, periodIDs: checkedId.map(item => item.id)
      }).then(res => {
        if (res.data.failedNum) {
          notification.open({
            message: messages('common.operate.filed')/*操作失败*/,
            description: <div>{res.data.failedReasons.map(item => <div>{item.periodName}:{item.errorMsg}</div>)}</div>,
            icon: <Icon type="frown-circle" style={{ color: '#e93652' }} />,
          });
        } else {
          message.success(messages('common.operate.success')/*操作成功*/);
        }
        this.setState({ editLoading: false });
        this.handleGoView();
        this[`${radio}Ref`].getList();
      }).catch(e => {
        this.setState({ editLoading: false });
        message.error(e.response.data.message)
      })
    }
  };

  handleGoEdit = () => {
    const { checkedId, radio } = this.state;
    let res = deepFullCopy(this.columns);
    res.map(item => {
      if (item.dataIndex === 'periodStatusCode') {
        item.title = radio === 'open'
          ? messages('finance-5.key40')/*操作状态*/
          : <Checkbox onChange={e => this.handleSelectAll(e)}>{messages('finance-5.key40')/*操作状态*/}</Checkbox>;
        item.render = (value, record) =>
          <Checkbox
            checked={!!checkedId.find(item => item.id === record.id)}
            onChange={e => this.handleCheck(e, record)}
          >
            {value === 'O' ? messages('finance-5.key41')/*关闭*/ : messages('finance-5.key42')/*打开*/}
          </Checkbox>
      }
      return item
    });
    this.setState({ isEditing: true, columns: res })
  };

  handleGoView = () => {
    this.setState({ isEditing: false, columns: deepFullCopy(this.columns), checkedId: [] });
  };

  handleCheck = (e, record) => {
    let { checkedId, radio } = this.state;
    if (e.target.checked) {
      radio === 'open' ? (checkedId[0] = record): checkedId.addIfNotExistObj(record, 'id');
    } else {
      checkedId.deleteObj(record, 'id');
    }
    this.setState({ checkedId });
  };

  handleSelectAll = e => {
    let { checkedId } = this.state;
    if (e.target.checked) {
      this.closeRef.state.dataSource.forEach(item => checkedId.addIfNotExistObj(item, 'id'));
    } else {
      this.closeRef.state.dataSource.forEach(item => checkedId.deleteObj(item, 'id'));
    }
    this.setState({ checkedId });
  };

  closeService = (page, size) => {
    const { periodSetId, setOfBooksId } = this.props.params;
    return httpFetch.get(`/api/periods/query/close`, {page, size, periodSetId, setOfBooksId})
  };

  openService = (page, size) => {
    const { periodSetId, setOfBooksId } = this.props.params;
    return httpFetch.get(`/api/periods/query/open`, {page, size, periodSetId, setOfBooksId})
  };

  render() {
    const { infoLoading, info, columns, radio } = this.state;
    return (
      <div className='account-detail'>
        <Info
          title='基本信息'
          attributes={this.attributes}
          dataSource={info}
          loading={infoLoading}
        />
        <Tabs defaultActiveKey={radio} onChange={key => {
          this.setState({ radio: key }, () => {
            this.handleGoView();
            this[`${key}Ref`].getList();
          })
        }}>
          <Tabs.TabPane tab={messages('finance-5.key43')/*会计期间未打开*/} key='close'>
            <div className='close-period'>
              <AdvanceTable.SimpleTable
                columns={columns}
                searchForm={[]}
                service={this.closeService}
                onRef={ref => this.closeRef = ref}
                rowKey='id'
              >
                {this.renderButton()}
              </AdvanceTable.SimpleTable>
            </div>
          </Tabs.TabPane>
          <Tabs.TabPane tab={messages('finance-5.key44')/*会计期间已打开*/} key='open'>
            <div className='open-period'>
              <AdvanceTable.SimpleTable
                columns={columns}
                searchForm={[]}
                service={this.openService}
                onRef={ref => this.openRef = ref}
                rowKey='id'
              >
                {this.renderButton()}
              </AdvanceTable.SimpleTable>
            </div>
          </Tabs.TabPane>
        </Tabs>
      </div>
    )
  }

}

export default PeriodControlDetail
